package com.example.springboot_manage.interceptor;

import com.alibaba.druid.util.StringUtils;
import com.example.springboot_manage.model.Account;
import com.example.springboot_manage.model.Admin;
import com.example.springboot_manage.service.AccountService;
import com.example.springboot_manage.util.CookieUtil;
import com.example.springboot_manage.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private AccountService accountService;
    @Value("${user.ticket}")
    private String userTicket;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //请求处理的方法之前执行
    //如果返回true ，执行下一个拦截器或者目标程序，如果返回false 不执行下一个拦截器或者目标
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String ticket = CookieUtil.getCookieValue(request,"userTicket");
        if (!StringUtils.isEmpty(ticket)){
            Admin admin = accountService.validate(ticket);
            if (admin==null){
                response.sendRedirect(request.getContextPath() + "/login");
                return  false;
            }
            request.getSession().setAttribute("user",admin);
            int id = accountService.findAdminId(admin);
            if (id!=0){
                Account account = accountService.findLoginInfo(id,ticket);
                request.getSession().setAttribute("loginInfo",account);
            }
            redisTemplate.opsForValue().set(userTicket + ":" + ticket, JsonUtil.object2JsonStr(admin)
            ,30, TimeUnit.MINUTES);
            return true;
        }
        response.sendRedirect(request.getContextPath() + "/login");
        return  false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
